package cn.faifai.desktop.view.dialog;

import cn.faifai.common.page.TableDataInfo;
import cn.faifai.desktop.api.TagController;
import cn.faifai.desktop.enums.SecondaryClickOperation;
import cn.faifai.desktop.events.ShowTagEditDialogEvent;
import cn.faifai.desktop.events.TagTreeItemSecondaryClickEvent;
import cn.faifai.desktop.events.TreeItemUpdateTagEvent;
import cn.faifai.common.utils.SpringContextUtil;
import cn.faifai.desktop.view.components.treeDirectory.TagBrowser;
import cn.faifai.desktop.viewModel.TagViewModel;
import cn.faifai.framework.utils.SingleEvenBus;
import cn.faifai.tagapi.dto.PageQuery;
import cn.faifai.tagapi.dto.TagDTO;
import cn.faifai.tagapi.dto.TagSerialize;
import cn.hutool.core.bean.BeanUtil;
import com.google.common.eventbus.Subscribe;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

@Slf4j
public class TagEditDialog {
    @Getter
    private BorderPane layout;
    private Long selectedTagId;
    private String operation;
    private Button addSubmitButton;
    private Button deleteSubmitButton;
    private Button updateSubmitButton;
    private Stage stage;
    private TagViewModel addTagViewModel;
    private TagViewModel updateTagViewModel;
    private String selectedTagName;
    private ListView<TagDTO> searchResultListView;
    private TextField searchField;
    private Button searchButton;
    private TreeItem selectedTagTreeItem;
//    private TagUpdateFlag tagUpdateFlag;

    // 单例模式
    private static class SingletonHolder {
        private static final TagEditDialog INSTANCE = new TagEditDialog();
    }

    public static TagEditDialog getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private TagEditDialog() {
    }

    public BorderPane initAddTagDialog(){
        BorderPane layout = new BorderPane();
        addTagViewModel = new TagViewModel();

        addTagViewModel.setParentId(selectedTagId);

        // 顶部：显示选中的标签名称
        Label selectedTagNameLabel = new Label("选中的父级标签: " + (StringUtils.isNotBlank(selectedTagName)? selectedTagName : "无"));
        layout.setTop(selectedTagNameLabel);
        BorderPane.setAlignment(selectedTagNameLabel, Pos.CENTER);

        // 中间：可编辑的数据 - 标签名称
        TextField tagNameField = new TextField();
        tagNameField.textProperty().bindBidirectional(addTagViewModel.nameProperty());
        layout.setCenter(tagNameField);
        BorderPane.setAlignment(tagNameField, Pos.CENTER);

        // 底部：添加按钮
        if (addSubmitButton == null) {
            addSubmitButton = this.initAddSubmitButton();
        }
        layout.setBottom(addSubmitButton);
        BorderPane.setAlignment(addSubmitButton, Pos.CENTER);

        // 设置边距或调整其他属性（如果需要）
        BorderPane.setMargin(selectedTagNameLabel, new Insets(10));
        BorderPane.setMargin(tagNameField, new Insets(10));
        BorderPane.setMargin(addSubmitButton, new Insets(10));

        return layout;
    }

    // todo 实现删除标签的对话框
    public BorderPane initDeleteTagDialog(){
        layout = new BorderPane();
        // 顶部：显示选中的标签名称
        Label selectedTagNameLabel = new Label("选中的标签: " + (StringUtils.isNotBlank(selectedTagName)? selectedTagName : "无"));
        layout.setTop(selectedTagNameLabel);
        BorderPane.setAlignment(selectedTagNameLabel, Pos.CENTER);
        if (deleteSubmitButton == null) {
            deleteSubmitButton = this.initDeleteSubmitButton();
        }
        layout.setBottom(deleteSubmitButton);
        BorderPane.setAlignment(deleteSubmitButton, Pos.CENTER);

        BorderPane.setMargin(selectedTagNameLabel, new Insets(10));
        BorderPane.setMargin(deleteSubmitButton, new Insets(10));

        return layout;
    }

    // todo 实现修改标签的对话框
    public BorderPane initUpdateTagDialog(){
        layout = new BorderPane();
        TagSerialize tag = SpringContextUtil.getContext().getBean(TagController.class).getTagById(selectedTagId);
        updateTagViewModel = new TagViewModel(BeanUtil.toBean(tag, TagDTO.class));

        // 顶部：显示选中的标签名称
        Label selectedTagNameLabel = new Label("选中的标签: " + (StringUtils.isNotBlank(selectedTagName)? selectedTagName : "无"));
        layout.setTop(selectedTagNameLabel);
        BorderPane.setAlignment(selectedTagNameLabel, Pos.CENTER);

        // 中间：编辑数据和搜索标签
        layout.setCenter(initCenterHBox());

        // 底部：添加按钮
        if (updateSubmitButton == null) {
            updateSubmitButton = this.initUpdateSubmitButton();
        }

        layout.setBottom(updateSubmitButton);
        BorderPane.setAlignment(updateSubmitButton, Pos.CENTER);

        BorderPane.setMargin(selectedTagNameLabel, new Insets(10));
//        BorderPane.setMargin(tagNameField, new Insets(10));
        BorderPane.setMargin(updateSubmitButton, new Insets(10));
        return layout;
    }


    // todo 初始化添加提交按钮
    private Button initAddSubmitButton() {
        Button submitButton = new Button("添加");
        submitButton.setOnAction(event -> {
            addTagViewModel.setId(null);
            TagController tagController = SpringContextUtil.getContext().getBean(TagController.class);
            boolean isSaved = tagController.save(addTagViewModel.toTagDTO()) != null;

            if (isSaved) {
                stage.close();
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("成功");
                alert.setHeaderText(null);
                alert.setContentText("标签添加成功！");
                alert.showAndWait();

                // 清空输入框
                addTagViewModel = new TagViewModel();

                SingleEvenBus.getInstance().post(new TreeItemUpdateTagEvent(selectedTagTreeItem,null));
            } else {
                // 处理保存失败的情况
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("错误");
                alert.setHeaderText(null);
                alert.setContentText("标签添加失败，请重试！");
                alert.showAndWait();
            }
        });
        return submitButton;
    }

    private Button initDeleteSubmitButton() {
        Button submitButton = new Button("删除");
        submitButton.setOnAction(event -> {
            TagController tagController = SpringContextUtil.getContext().getBean(TagController.class);
            boolean isDeleted = tagController.delete(Arrays.asList(selectedTagId)) != null;

            if (isDeleted) {
                stage.close();
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("成功");
                alert.setHeaderText(null);
                alert.setContentText("标签删除成功！");
                alert.showAndWait();
                SingleEvenBus.getInstance().post(new TreeItemUpdateTagEvent(selectedTagTreeItem.getParent(), null));
            }
        });
        return submitButton;
    }

    private Button initUpdateSubmitButton() {
        Button submitButton = new Button("修改");
        submitButton.setOnAction(event -> {
            TagController tagController = SpringContextUtil.getContext().getBean(TagController.class);
            boolean isUpdated = tagController.save(updateTagViewModel.toTagDTO()) != null;

            if (isUpdated) {
                stage.close();
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("成功");
                alert.setHeaderText(null);
                alert.setContentText("标签修改成功！");
                alert.showAndWait();
                SingleEvenBus.getInstance().post(new TreeItemUpdateTagEvent(selectedTagTreeItem.getParent(), updateTagViewModel.getParentId()));
            } else {
                // 处理保存失败的情况
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("错误");
                alert.setHeaderText(null);
                alert.setContentText("标签修改失败，请重试！");
                alert.showAndWait();
            }
        });
        return submitButton;
    }

    private Button initSearchButton() {
        Button newButton = new Button("搜索");
        newButton.setOnAction(event -> {
            TagController tagController = SpringContextUtil.getContext().getBean(TagController.class);
            TableDataInfo<TagDTO> tagDTOData = tagController.getTagDTOPageList(new TagDTO(searchField.getText()), new PageQuery(1, 10));
            searchResultListView.setItems(FXCollections.observableList(tagDTOData.getRows()));
        });
        return newButton;
    }

    private HBox initCenterHBox() {
        // 左侧：可编辑的数据 - 标签名称
        GridPane leftBox = new GridPane();
        leftBox.setHgap(10); // 设置水平间距
        leftBox.setVgap(10); // 设置垂直间距

        // 创建Label和TextField
        Label tagNameLabel = new Label("标签名称:");
        TextField tagNameField = new TextField();
        tagNameField.textProperty().bindBidirectional(updateTagViewModel.nameProperty());

        Label parentTagNameLabel = new Label("父标签名称:");
        TextField parentTagNameField = new TextField();
        parentTagNameField.textProperty().bindBidirectional(updateTagViewModel.parentTagNameProperty());
        parentTagNameField.setEditable(false);

        // 添加到GridPane中，确保第一列的所有Label宽度相同
        leftBox.add(tagNameLabel, 0, 0);
        leftBox.add(tagNameField, 1, 0);

        leftBox.add(parentTagNameLabel, 0, 1);
        leftBox.add(parentTagNameField, 1, 1);

        // 右侧：搜索框
        searchField = new TextField();
        searchField.setPromptText("输入标签搜索...");
        searchButton = initSearchButton();
        HBox hBox = new HBox(searchField, searchButton);
        hBox.setSpacing(20);
        searchResultListView = new ListView<>(FXCollections.observableList(Arrays.asList(new TagDTO("请在这里搜索并双击选中父标签"))));
        searchResultListView.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                if (event.getEventType() == MouseEvent.MOUSE_CLICKED){
                    TagDTO selectedItem = searchResultListView.getSelectionModel().getSelectedItem();
                    updateTagViewModel.setParentTagName(selectedItem.getName());
                    updateTagViewModel.setParentId(selectedItem.getId());
//                    tagUpdateFlag = TagUpdateFlag.PARENT_UPDATE;
                }
            }
        });
        VBox search = new VBox(hBox, searchResultListView);
        search.setSpacing(10);

        // 创建用于平分中心区域的HBox
        HBox centerHBox = new HBox();
        centerHBox.setPadding(new Insets(10));

        // 设置VBox作为左右两侧的内容容器
        VBox rightVBox = new VBox(search);

        // 使用Region作为占位符以平衡空间
        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS); // 使得spacer能够扩展并占据可用空间

        // 将leftVBox、spacer和rightVBox添加到centerHBox中
        centerHBox.getChildren().addAll(leftBox, spacer, rightVBox);

        return centerHBox;
    }

    @Subscribe
    public void handleShowTagEditDialogEvent(ShowTagEditDialogEvent event) {
        log.info("收到显示标签编辑对话框事件: {}", event.getOperation());
        this.operation = event.getOperation();
        if (stage != null) stage.close();
        stage = new Stage();
        if (this.operation.equals(SecondaryClickOperation.ADD.getOperation())){
            stage.setScene(new Scene(initAddTagDialog(), 300, 125));
        } else if (this.operation.equals(SecondaryClickOperation.DELETE.getOperation())){
            stage.setScene(new Scene(initDeleteTagDialog(), 300, 125));
        } else if (this.operation.equals(SecondaryClickOperation.UPDATE.getOperation())){
            stage.setScene(new Scene(initUpdateTagDialog(), 550, 500));
        }
        stage.setTitle(this.operation);
        stage.show();
    }

    @Subscribe
    public void handleTagSelectedEvent(TagTreeItemSecondaryClickEvent event) {
        log.info("收到选中标签: {}", event.getTagId());
        selectedTagId = event.getTagId();
        selectedTagName = event.getName();

        if (event.getSelectedTreeItem().getValue() instanceof TagBrowser.TagItem){
            TagBrowser.TagItem value = (TagBrowser.TagItem) event.getSelectedTreeItem().getValue();
            log.info("收到选中项: {}", value.getName());
            selectedTagTreeItem = event.getSelectedTreeItem();
        }

    }


}
